/**
 * NetUitl 网络请求的实现
 * https://github.com/facebook/react-native
 */
import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ListView,
    Image,
    TouchableOpacity,
    Platform,
    AsyncStorage
} from 'react-native';
import UrlUtils from "./UrlCollection";

export default class NetUtil extends Component {

    /**
     * get请求
     * @param url 请求地址
     * @param params 参数
     * @param callback 回调函数
     */
    static get (url, params, callback) {
        if (params) {
            let paramsArray = [];
            //拼接参数
            url = UrlUtils.moorsBaseUrl + url;
            Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]));
            if (url.search(/\?/) === -1) {
                url += '?' + paramsArray.join('&')
            } else {
                url += '&' + paramsArray.join('&')
            }
        }
        // fetch请求
        fetch(url, {
            method: 'GET',
        }).then((response) => {
            return response.json()
        }).then((responseData) => {
            callback(responseData)
         }).
        catch((error)=>{
            console.error(error)
        }).done();
    }

    /*
     *  post表单提交
     *  url:请求地址
     *  params:参数
     *  callback:回调函数
     * */
    static postForm(url, params, callbackSuccess, callbackError) {
        //fetch请求

        url=UrlUtils.moorsBaseUrl+url;
        let opt = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: params
        };

        fetch(url, opt)
            .then((response) => response.json())
            .then((responseJSON) => {
                callbackSuccess(responseJSON)
            })
            .catch((error) => {
                if (error)
                    callbackError(error)
            }).done();

    }

}